﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SchoolManagementSystem.Controls;
using SchoolManagementSystem.Forms.BusinessForm;
using CoreData;
using SchoolManagementSystem.Details;
using Helper;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Repository;
using SchoolManagementSystem.Report._4._Kho;

namespace SchoolManagementSystem.Forms.BusinessForm
{
    public partial class Stock_VoucherInForm : DetailForm
    {
        long id;
        public List<long> VoucherSeletedProductID { get; set; }
        public long ProviderID { get; set; }
        private long VoucherInID { get; set; }
        public Stock_VoucherInForm()
        {
            InitializeComponent();
            //this.id = id;
            //Create column TotalAmount
            gridControl1.ForceInitialize();
            //DevExpress.XtraGrid.Columns.GridColumn unbColumn = gridView1.Columns.AddField("TotalAmount");
            //unbColumn.VisibleIndex = gridView1.Columns.Count;
            //unbColumn.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            //unbColumn.OptionsColumn.AllowEdit = false;
            //unbColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //unbColumn.DisplayFormat.FormatString = "c0";
            //unbColumn.AppearanceCell.BackColor = Color.LemonChiffon;
            gridControl1.DataSource = CreateTable();
            //end create
            dateEdit_create.Text = DateTime.Now.ToShortDateString();
            comboboxUC_PaymentMethod.Model = RegisterService.RegisterServices.PaymentMethodService;
            comboboxUC_PaymentMethod.Uc = new Payment_MethodUC();
            comboboxUC_PaymentMethod.ColumnMain = "Name";
            comboboxUC_PaymentMethod.ColumnDisplay = "Code,Name";

            //comboboxUC_StockInputMethod.Model = RegisterService.RegisterServices.StockMethodService;
            //comboboxUC_StockInputMethod.Uc = new StockMethodUC();
            //comboboxUC_StockInputMethod.ColumnMain = "Name";
            //comboboxUC_StockInputMethod.ColumnDisplay = "Code,Name";
            //comboboxUC_Stock.SelectedValue = "1";

            comboboxUC_Stock.Model = RegisterService.RegisterServices.ProductWareHouseService;
            comboboxUC_Stock.Uc = new StockUC();
            comboboxUC_Stock.ColumnMain = "Name";
            comboboxUC_Stock.ColumnDisplay = "Code,Name";
            //comboboxUC_Stock.SelectedValue = "1";

            combobox_Staff.Model = RegisterService.RegisterServices.StaffService;
            combobox_Staff.Uc = new StaffUC();
            combobox_Staff.ColumnMain = "Name";
            combobox_Staff.ColumnDisplay = "ID,Name";
            combobox_Staff.SelectedValue = ValueDefine.StaffID.ToString();
            combobox_Staff.Enabled = false;

            combobox_Provider.Model = RegisterService.RegisterServices.ProductProviderService;
            combobox_Provider.Uc = new Product_ProviderUC();
            combobox_Provider.ColumnMain = "Name";
            combobox_Provider.ColumnDisplay = "ID,Name";

            lookUpEdit_StockInOutMethod.Properties.DataSource = RegisterService.RegisterServices.StockMethodService.GetListByType("IN");
            lookUpEdit_StockInOutMethod.Properties.ValueMember = "ID";
            lookUpEdit_StockInOutMethod.Properties.DisplayMember = "Name";
            lookUpEdit_StockInOutMethod.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Đơn vị tính"));
            lookUpEdit_StockInOutMethod.ItemIndex = 1;

            //Khoi tao gia tri cho control
            comboBoxEdit_VAT.SelectedIndex = 0;
            if (checkCodeAuto.Checked == true)
                txtcode.Enabled = false;
            {
                txtcode.Text = RegisterService.RegisterServices.StockVoucherInService.GetVoucherNo("PNK");
            }



        }
        public DialogResult ShowDialog(long VoucherID)
        {
            Stock_VoucherIn objVoucher = new Stock_VoucherIn();
            if (VoucherID > 0)
            {
                cmdaddproduct.Enabled = false;
                VoucherInID = VoucherID;
                objVoucher = (Stock_VoucherIn)RegisterService.RegisterServices.StockVoucherInService.GetByID(VoucherID);
                btnPrintVoucherInPropose.Enabled = false;
            }
            txtcode.Text = objVoucher.VoucherInNo;
            txtbillno.Text = objVoucher.BillNo;
            dateEdit_create.DateTime = objVoucher.VoucherDate;
            combobox_Provider.ID = objVoucher.WarehouseID;
            combobox_Staff.ID = objVoucher.EmployeeID;
            comboboxUC_Stock.ID = objVoucher.WarehouseID;
            comboboxUC_PaymentMethod.ID = objVoucher.Payment_MethodID;
            lookUpEdit_StockInOutMethod.EditValue = objVoucher.Input_MethodID;
            txtnote.Text = objVoucher.Note;
            txtSumPrice.Text = objVoucher.Amount.ToString();
            if (objVoucher.VAT == false)
            {
                comboBoxEdit_VAT.SelectedIndex = 0;
                txtVATAmount.Text = "0";
            }
            else
            {
                comboBoxEdit_VAT.SelectedIndex = 1;
                txtVATAmount.Text = (objVoucher.Amount * 10 / 100).ToString();
            }
            txtTotalAmount.Text = objVoucher.TotalAmount.ToString();

            //Load Detail
            IList<Stock_VoucherInDetail> listdetail = RegisterService.RegisterServices.StockVoucherInDetailService.GetListVIDByPID(VoucherID);
            int newRowHandle;
            if (listdetail != null || listdetail.Count > 0)
            {
                IList<Product_Unit> listUnit = (IList<Product_Unit>)RegisterService.RegisterServices.ProductUnitService.GetList();
                if (listUnit.Count > 0)
                {
                    //repositoryItemLookUpEdit_Unit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
                    repositoryItemLookUpEdit_Unit.DataSource = listUnit;
                }
                repositoryItemLookUpEdit_Unit.ValueMember = "ID";
                repositoryItemLookUpEdit_Unit.DisplayMember = "Name";
                repositoryItemLookUpEdit_Unit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Đơn vị tính"));
                foreach (var ilist in listdetail)
                {
                    gridView1.AddNewRow();
                    newRowHandle = gridView1.FocusedRowHandle;
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductNameExt"], ilist.ProductNameExt);
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductID"], ilist.ID);
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductCodeExt"], ilist.ProductCodeExt);
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Quantity"], ilist.Quantity);
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Price"], ilist.Price);
                    //
                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Amount"], ilist.Price * ilist.Quantity);
                    //lay danh sach don vi tinh

                    gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["UnitNameExt"], ilist.UnitID);
                    gridView1.UpdateCurrentRow();
                }
                gridView1.RefreshData();
                UpdateTotal();
                gridView1.OptionsBehavior.Editable = false;
            }

            // end load detail
            this.ShowDialog();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            return this.DialogResult;
        }
        void SetGridValue(DevExpress.XtraGrid.Views.Grid.GridView view)
        {

        }


        private void cmdaddproduct_Click(object sender, EventArgs e)
        {

            frmSelectProduct pro = new frmSelectProduct();

            VoucherSeletedProductID = new List<long>();
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                VoucherSeletedProductID.Add(Convert.ToInt64(gridView1.GetRowCellValue(i, "ProductID")));
            }
            ProviderID = combobox_Provider.ID;
            if (pro.ShowDialog(VoucherSeletedProductID, ProviderID) == DialogResult.OK)
            {
                IList<Product> listproduct = new List<Product>();
                listproduct = RegisterService.RegisterServices.ProductService.GetProductInListID(pro.ProductSeletedIDs);
                int newRowHandle;
                if (listproduct != null)
                {
                    IList<Product_Unit> listUnit = (IList<Product_Unit>)RegisterService.RegisterServices.ProductUnitService.GetList();
                    if (listUnit.Count > 0)
                    {
                        //repositoryItemLookUpEdit_Unit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
                        repositoryItemLookUpEdit_Unit.DataSource = listUnit;
                    }
                    repositoryItemLookUpEdit_Unit.ValueMember = "ID";
                    repositoryItemLookUpEdit_Unit.DisplayMember = "Name";
                    repositoryItemLookUpEdit_Unit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Đơn vị tính"));
                    foreach (var iproduct in listproduct)
                    {
                        gridView1.AddNewRow();
                        newRowHandle = gridView1.FocusedRowHandle;
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductNameExt"], iproduct.Name);
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductID"], iproduct.ID);
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["ProductCodeExt"], iproduct.Code);
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Quantity"], 1);
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Price"], iproduct.Input_Price);
                        //
                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["Amount"], iproduct.Input_Price);
                        //lay danh sach don vi tinh
                        //IList<Product_UnitChange> listUnit = (IList<Product_UnitChange>)RegisterService.RegisterServices.ProductUnitChangeService.GetUnitChangeByProductID(iproduct.ID);

                        gridView1.SetRowCellValue(newRowHandle, gridView1.Columns["UnitNameExt"], iproduct.Input_UnitID);
                        gridView1.UpdateCurrentRow();
                    }
                    gridView1.RefreshData();
                    UpdateTotal();
                    SaveAble = true;
                    gridView1.Focus();
                }
            }
        }

        void UpdateTotal()
        {
            decimal iteamPrice = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                iteamPrice += Convert.ToDecimal(gridView1.GetRowCellValue(i, "Amount"));
            }
            txtSumPrice.Text = iteamPrice.ToString();
            decimal vat = 0;
            if (comboBoxEdit_VAT.Text == "10%")
                vat = iteamPrice * 10 / 100;
            txtTotalAmount.Text = (iteamPrice + vat).ToString();
        }
        private DataTable CreateTable()
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("ProductNameExt", typeof(string));
            tbl.Columns.Add("ProductID", typeof(int));
            tbl.Columns.Add("ProductCodeExt", typeof(string));
            tbl.Columns.Add("Quantity", typeof(int));
            tbl.Columns.Add("Price", typeof(decimal));
            tbl.Columns.Add("UnitNameExt", typeof(int));
            tbl.Columns.Add("Amount", typeof(decimal));
            return tbl;
        }
        /// <summary>
        /// Get TotalAmount
        /// </summary>
        /// <param name="view">gridview</param>
        /// <param name="listSourceRowIndex">row index</param>
        /// <returns>decimal total amount</returns>
        decimal getTotalValue(DevExpress.XtraGrid.Views.Grid.GridView view, int listSourceRowIndex)
        {
            if (view.Columns["Price"] != null || view.Columns["Quantity"] != null)
            {
                decimal unitPrice = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Price"));
                decimal quantity = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Quantity"));
                return unitPrice * quantity;
                            }
            else
                return 0;
        }
        //int chk = 0;
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (gridView1.IsEditing)
            {
                if (e.Column.FieldName == "Quantity" || e.Column.FieldName == "Price")
                {
                    gridView1.SetRowCellValue(e.RowHandle, gridView1.Columns["Amount"], getTotalValue(gridView1, e.RowHandle));
                    gridView1.UpdateCurrentRow();
                    gridView1.RefreshData();
                    UpdateTotal();
                }
                //điều chỉnh tiền thuế nếu có
                decimal vat = 0;
                decimal iteamPrice = Convert.ToDecimal(txtSumPrice.Text);
                if (comboBoxEdit_VAT.Text == "10%")
                    vat = Convert.ToDecimal(txtSumPrice.Text) * 10 / 100;
                txtTotalAmount.Text = (iteamPrice + vat).ToString();
                txtVATAmount.Text = vat.ToString();
                //long _ProductID = Convert.ToInt64(gridView1.GetListSourceRowCellValue(e.RowHandle, "ProductID"));
                //IList<Product_UnitChange> listUnit = (IList<Product_UnitChange>)RegisterService.RegisterServices.ProductUnitChangeService.GetUnitChangeByProductID(_ProductID);
                //long _UnitChangeID = Convert.ToInt64(gridView1.GetListSourceRowCellValue(e.RowHandle, "UnitNameExt"));
                //if ((listUnit != null || listUnit.Count > 0) && listUnit[0].UnitID != _UnitChangeID)
                //{
                   
                //    if (e.Column.FieldName == "UnitNameExt")
                //    {
                       
                //        decimal _price = RegisterService.RegisterServices.ProductService.GetPriceByUnit(_UnitChangeID, _ProductID);
                //        gridView1.SetRowCellValue(e.RowHandle, gridView1.Columns["Price"], _price);
                //        UpdateTotal();
                //        gridView1.UpdateCurrentRow();
                //        gridView1.RefreshData();
                //    }
                //}
                //else if (chk == 0 && listUnit[0].UnitID!=_UnitChangeID)
                //{
                //    chk += 1;
                //    string acceptstr = "";
                //    foreach (var item in listUnit)
                //    {
                //        acceptstr += "- "+item.NameExt+"\n";
                //    }
                //    string dispText = gridView1.GetRowCellDisplayText(e.RowHandle, "UnitNameExt");
                //    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UnitNameExt"], listUnit[0].UnitID);
                //    MessageBox.Show("Đơn vị tính: \"" +  dispText+ "\" chưa quy đổi\nCác đơn vị tính hợp lệ:\n " + acceptstr, "Không hợp lệ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //}
            }
            //chk = 0;

        }

        void LoadData()
        {
            if (id != 0)
            {
                var data = RegisterService.RegisterServices.StockVoucherInService.GetByID(id);

            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (e.Column.FieldName == "Amount" && e.IsGetData) e.Value = getTotalValue(view, e.ListSourceRowIndex);
        }

        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //if (gridView1.IsEditing)
            //{
            //    if (e.Column.FieldName == "Quantity" || e.Column.FieldName == "Price")
            //    {
            //        gridView1.SetRowCellValue(e.RowHandle, gridView1.Columns["TotalAmount"], getTotalValue(gridView1, e.RowHandle));
            //        gridView1.UpdateCurrentRow();
            //        gridView1.RefreshData();
            //    }
            //}

        }

        private void comboBoxEdit_VAT_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtSumPrice.Text != string.Empty)
            {
                decimal vat = 0;
                decimal iteamPrice = Convert.ToDecimal(txtSumPrice.Text);
                if (comboBoxEdit_VAT.Text == "10%")
                    vat = Convert.ToDecimal(txtSumPrice.Text) * 10 / 100;
                txtTotalAmount.Text = (iteamPrice + vat).ToString();
                txtVATAmount.Text = vat.ToString();
            }
        }
        private string ValidateVoucher()
        {
            string message = string.Empty;
            if (combobox_Provider.ID <= 0)
            {
                message += "Chưa chọn nhà cung cấp\n";
            }
            if (comboboxUC_PaymentMethod.ID <= 0)
            {
                message += "Chưa chọm phương thức thanh toán\n";
            }
            if (lookUpEdit_StockInOutMethod.EditValue == null)
            {
                message += "Chưa chọn phương thức nhập\n";
            }
            return message;
        }
        protected override void Print()
        {
           // frmReportDetailForm frm = new frmReportDetailForm();
           // frm.ShowDialog(VoucherInID, "VoucherInForm");
        }

        protected override long Save()
        {
            string validateString = ValidateVoucher();
            if (validateString != string.Empty)
            {
                MessageBox.Show(validateString, "Nhập liệu", MessageBoxButtons.OK);
                return -1;
            }
            Stock_VoucherIn voucherIn = new Stock_VoucherIn();
            if (ID > 0)
            {
                voucherIn = (Stock_VoucherIn)RegisterService.RegisterServices.StockVoucherInService.GetByID(ID);
                voucherIn.LastModifiedBy = ValueDefine.StaffID;
                voucherIn.LastModifiedDate = DateTime.Now;
            }
            else
            {
                voucherIn.CreatedBy = ValueDefine.StaffID;
                voucherIn.CreatedDate = DateTime.Now;
                voucherIn.LastModifiedBy = ValueDefine.StaffID;
                voucherIn.LastModifiedDate = DateTime.Now;
            }
            voucherIn.VoucherInNo = txtcode.Text;
            voucherIn.BillNo = txtbillno.Text;
            voucherIn.VoucherDate = DateTime.Now; //dateEdit_create.DateTime;
            //voucherIn.provider
            voucherIn.CreatedDate = dateEdit_create.DateTime;
            voucherIn.Input_MethodID = (long)lookUpEdit_StockInOutMethod.EditValue;
            voucherIn.Note = txtnote.Text;
            voucherIn.WarehouseID = comboboxUC_Stock.ID;
            voucherIn.Payment_MethodID = comboboxUC_PaymentMethod.ID;
            voucherIn.EmployeeID = combobox_Staff.ID;
            voucherIn.Amount = Convert.ToDecimal(txtSumPrice.Text);
            voucherIn.Active = true;
            if (txtVATAmount.Text == "0")
                voucherIn.VAT = true;
            else
                voucherIn.VAT = false;
            voucherIn.TotalAmount = Convert.ToDecimal(txtTotalAmount.Text);
            ID = RegisterService.RegisterServices.StockVoucherInService.Save(voucherIn);
            
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                Stock_VoucherInDetail voucherDetail= new Stock_VoucherInDetail();
                voucherDetail.ProductID = Convert.ToInt64(gridView1.GetRowCellValue(i, "ProductID"));
                voucherDetail.Quantity = Convert.ToInt32(gridView1.GetRowCellValue(i, "Quantity"));
                voucherDetail.UnitID = Convert.ToInt64(gridView1.GetRowCellValue(i, "UnitNameExt"));
                voucherDetail.Price = Convert.ToDecimal(gridView1.GetRowCellValue(i, "Price"));
                voucherDetail.Amount = Convert.ToDecimal(gridView1.GetRowCellValue(i, "Amount"));
                voucherDetail.Stock_VoucherInID = ID;
                long a = RegisterService.RegisterServices.StockVoucherInDetailService.Save(voucherDetail);
            }
            VoucherInID = ID;
            this.Close();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            return ID;
        }
        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {


        }

        private void gridView1_CustomRowCellEditForEditing(object sender, CustomRowCellEditEventArgs e)
        {
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (gridView1.SelectedRowsCount > 0)
                {
                    if (MessageBox.Show("Bạn có chắc muốn xóa dữ liệu đã chọn trong danh sách?", "Xóa dữ liệu", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                    { gridView1.DeleteSelectedRows(); }
                }
                else
                {
                    MessageBox.Show("Chọn dữ liệu cần xóa trong danh sách", "Xóa dữ liệu", MessageBoxButtons.OK);
                }
            }

        }
        
        private void btnPrintVoucherInPropose_Click(object sender, EventArgs e)
        {
            Stock_VoucherIn voucherInPropose = new Stock_VoucherIn();
            voucherInPropose.VoucherInNo = txtcode.Text;
            voucherInPropose.BillNo = txtbillno.Text;
            voucherInPropose.VoucherDate = dateEdit_create.DateTime;
            //voucherIn.provider
            voucherInPropose.CreatedDate = dateEdit_create.DateTime;
            //voucherInPropose.Input_MethodID = (long)lookUpEdit_StockInOutMethod.EditValue;
            //voucherInPropose.Note = txtnote.Text;
            voucherInPropose.WarehouseID = comboboxUC_Stock.ID;
            voucherInPropose.PaymentMethodNameExt = comboboxUC_PaymentMethod.SelectedValue;
            voucherInPropose.EmployeeNameExt = combobox_Staff.SelectedValue;
            voucherInPropose.Amount = Convert.ToDecimal(txtSumPrice.Text);
            voucherInPropose.Active = true;

            List<Stock_VoucherInDetail> listVoucherInDetail = new List<Stock_VoucherInDetail>();
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                Stock_VoucherInDetail voucherDetail = new Stock_VoucherInDetail();
                voucherDetail.ProductCodeExt = Convert.ToString(gridView1.GetRowCellValue(i, "ProductCodeExt"));
                voucherDetail.ProductNameExt = Convert.ToString(gridView1.GetRowCellValue(i, "ProductNameExt"));
                voucherDetail.Quantity = Convert.ToInt32(gridView1.GetRowCellValue(i, "Quantity"));
                voucherDetail.UnitNameExt = repositoryItemLookUpEdit_Unit.GetDisplayText(gridView1.GetRowCellValue(i, "UnitNameExt"));//Convert.ToString(gridView1.GetRowCellValue(i, "UnitNameExt"));
                voucherDetail.Price = Convert.ToDecimal(gridView1.GetRowCellValue(i, "Price"));
                voucherDetail.Amount = Convert.ToDecimal(gridView1.GetRowCellValue(i, "Amount"));
                listVoucherInDetail.Add(voucherDetail);
                
            }
            frmReportDetailForm frm = new frmReportDetailForm();
            frm.ShowDialog(voucherInPropose, listVoucherInDetail);
        }

        private void checkCodeAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (checkCodeAuto.Checked == true)
                txtcode.Enabled = false;
            else
            { txtcode.Enabled = true; txtcode.Text = RegisterService.RegisterServices.StockVoucherInService.GetVoucherNo("PNK"); }
        }


    }


}